import { create } from "zustand";
import { createJSONStorage, devtools, persist } from "zustand/middleware";

export interface TabPageItem {
	url: string;
	title: string;
}

export interface TabPagesState {
	tabPages: TabPageItem[];
	getTabPages: () => TabPageItem[];
	addTabPage: (tabPage: TabPageItem) => void;
	updateTabPage: (tabPage: TabPageItem) => void;
	removeTabPage: (url: string) => void;
	findTabPageIndex: (url: string) => number;
	findTabPage: (url: string) => TabPageItem | undefined;
}

export const useTabPagesStore = create<TabPagesState>()(
	devtools(
		persist(
			(set, get) => ({
				tabPages: [],
				getTabPages: () => get().tabPages,
				addTabPage: (tabPage: TabPageItem) => {
					const { tabPages } = get();
					const index = tabPages.findIndex((item) => item.url === tabPage.url);
					if (index === -1) {
						set({ tabPages: [...tabPages, tabPage] });
					}
				},
				updateTabPage: (tabPage: TabPageItem) => {
					const { tabPages } = get();
					const newTabPages = tabPages.map((item) => {
						if (item.url === tabPage.url) {
							return tabPage;
						}
						return item;
					});
					set({ tabPages: newTabPages });
				},
				removeTabPage: (url: string) => {
					const { tabPages } = get();
					const index = tabPages.findIndex((item) => item.url === url);
					if (index !== -1) {
						set({ tabPages: tabPages.filter((item) => item.url !== url) });
					}
				},
				findTabPageIndex: (url: string) => {
					const { tabPages } = get();
					return tabPages.findIndex((item) => item.url === url);
				},
				findTabPage: (url: string) => {
					const { tabPages } = get();
					return tabPages.find((item) => item.url === url);
				},
			}),
			{
				name: "tab-pages",
				storage: createJSONStorage(() => sessionStorage),
			},
		),
	),
);
